class TreeFlat {
  constructor({ flatNodes = [], tree = {} }) {
    this.flatNodes = flatNodes;
    this.tree = tree;
  }
  toFlat(childrenCN = "children") {
    this.flatNodes = [];
    this.treeToFlat(this.tree, childrenCN);
    return this.flatNodes;
  }
  treeToFlat(tree, childrenCN = "children") {
    let childrenTrees = tree[childrenCN];
    this.flatNodes.push(tree);

    if (Array.isArray(childrenTrees) && childrenTrees.length > 0) {
      //后置处理函数
      // tree 转 pureNode
      tree[childrenCN] = [];

      childrenTrees.forEach((newTree) => {
        this.treeToFlat(newTree, childrenCN);
      });
    }
    //eslint 不喜欢空着的代码块
    // else {

    // }
  }
  flatToTree(pureNode) {
    let childrenNodes = this.flatNodes.filter(
      (node) => node.pid === pureNode.id
    );
    if (Array.isArray(childrenNodes) && childrenNodes.length > 0) {
      pureNode.children = childrenNodes;

      childrenNodes.forEach((newPureNode) => {
        this.flatToTree(newPureNode);
      });
    } else {
      pureNode.children = [];
    }
  }
  toTree() {
    this.tree = {};
    let pureRootNode = this.flatNodes.find((node) => node.id === 0);
    this.tree = pureRootNode;
    // console.log("pureRootNode", pureRootNode);
    this.flatToTree(pureRootNode);
    return this.tree;
  }
  // 数据库 -》 用户  flat -> tree
  toTreeDirect(ID = "id", PID = "pid") {
    //小蝌蚪找父亲
    this.flatNodes.forEach((childNode) => {
      let parentNode = this.flatNodes.find(
        (parentNode) => parentNode[ID] === childNode[PID]
      );
      if (parentNode) {
        parentNode.children.push(childNode);
      }
    });
    //拿出root
    this.tree = this.flatNodes.find((n) => n[ID] === 0);
    console.log("root", this.tree);
    return this.tree;
  }
}
export default TreeFlat;